from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse, HttpResponseBadRequest
from collections import OrderedDict
from apps.goods.models import GoodsChannel
from utils.views import LoginRequiredJsonMixin
from apps.contents.models import ContentCategory
from utils.goods import get_categories, get_breaddata, get_goods_specs
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
# django分页器
from django.core.paginator import Paginator, EmptyPage
from haystack.views import SearchView
from datetime import date
import json
from django_redis import get_redis_connection

class UserVisitLogView(LoginRequiredJsonMixin, View):
    '''用户浏览记录'''
    def post(self, request):
        # 拿到商品的sku_id
        josn_dict = json.loads(request.body.decode())
        sku_id = josn_dict['sku_id']

        # 存储到redis，key为history_user.id
        redis_coun = get_redis_connection('history')
        pl = redis_coun.pipeline()
        user_id = request.user.id
        # 使用列表的方式存储
        # 先去重
        pl.lrem('history_%s' % user_id, 0, sku_id)

        # 存储
        pl.lpush('history_%s' % user_id, sku_id)

        # 截取５个数据
        pl.ltrim('history_%s' % user_id, 0, 4)

        pl.execute()

        # 响应结果
        return JsonResponse({'code': 0, 'errmsg': 'OK'})




    def get(self, request):
        '''返回数据'''
        # 查询数据
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)


        # 遍历sku_ids用sku_id在数据库查询

        lists = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            lists.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'skus': lists})




# ===============================================================================================================
class CountShopVisitView(View):
    '''统计商品访问量'''
    def post(self, request, category_id):
        # 通过category_id拿到商品数据
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return HttpResponseBadRequest('数据错误')


        # 获取当天时间
        today_date = date.today()


        # 判断当天商品是否存在不存在创建存在累加
        try:
            count_shop = category.goodsvisitcount_set.get(date=today_date)

        except:
            # 没有就创建
            count_shop = GoodsVisitCount()

        try:
            count_shop.count += 1
            count_shop.category = category
            count_shop.save()
        except Exception as e:
            return HttpResponseBadRequest('no')

        return JsonResponse({'code': 0, 'errmsg': 'OK'})





# =====================================================================================================

class DetailView(View):
    '''商品详情页'''
    def get(self, request, sku_id):
        # 获取当前sku信息
        try:
            skus = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('没有拿到skus')

        # 查询商品频道分类
        categories = get_categories()

        # 查询面包屑数据
        breadcrumb = get_breaddata(skus.category)

        goods_specs = get_goods_specs(skus)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': skus,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)



# ========================================================================================================

class MySearchView(SearchView):
    '''重写SearchView类'''

    def create_response(self):
        page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        # 拼接参数, 返回
        return JsonResponse(data_list, safe=False)


# ================================================================================================

class HotShopView(View):
    '''热销排行'''
    def get(self, request, category_id):

        try:
            skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[0:2]
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('数据执行失败')

        # 准备数据
        lists = []
        for sku in skus:
            lists.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price,

            })

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': lists})








# =============================================================================================

class ShopListView(View):
    '''商品列表页'''

    def get(self, request, category_id):
        # 获取参数
        '''
        /list/115/skus/?page=1&page_size=5&ordering=-create_time
        '''
        page = request.GET.get('page')  # 当前页码
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        try:
            # 用category_id拿到三级分类信息
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist as e:
            return HttpResponseBadRequest('数据库查询错误')

        # 通过category拿到面包屑数据
        breadbata = get_breaddata(category)


        # 拿到排序sku商品的数据

        try:
            skus = SKU.objects.filter(category_id=category, is_launched=True).order_by(ordering)
        except SKU.DoesNotExist as e:
            return HttpResponseBadRequest('数据库查询错误')


        # 将数据分页
        # 创建分页器对象传入数据list 一页最大展示
        paginator = Paginator(skus, page_size)

        # 获取每页商品数据
        try:
            paginator_data = paginator.page(page)
        except EmptyPage: # 分页器自带的错误
            return HttpResponseBadRequest('no')

        # 获得列表页的总页数
        total_page = paginator.num_pages

        # 定义List将单个数据对象字典化
        lists = []
        # 一页一页的遍历
        for sku in paginator_data:
            lists.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })


        # 向前端发送
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'breadcrumb': breadbata,
            'list': lists,
            'count': total_page
        })










# =========================================================================================================================

class IndexView(View):
    """首页广告"""

    def get(self, request):
        """
        提供首页广告界面
        """
        # 查询商品频道和分类
        categories = get_categories()

        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')


        # 渲染模板的上下文
        context = {
            'categories': categories,
            'contents': contents,
            }



        return render(request, 'index.html', context)